const { contextBridge, ipcRenderer } = require("electron");
const clipboard = require("electron").clipboard;
const utils = require("./utils/utils");
const Vue = require("./lib/vue2.7.7.js");
const elementui = require("./lib/element-ui/index.js");
let $ = null;
Vue.use(elementui);
contextBridge.exposeInMainWorld("electronAPI", {
    //主进程向渲染进程通讯
    onMsessage: (callback) => ipcRenderer.on("main", callback),
    //渲染进程向主进程通讯
    sendMessage: (msg) => sendMsg(msg),
});

function sendMsg(msg) {
    return ipcRenderer.invoke("asynchronous-message", msg);
}

function goBack() {
    let data = {
        cmd: "loadFile",
        type: "main",
        url: "index.html",
    };
    return sendMsg(data);
}

function regBack(dom) {
    dom.addEventListener("click", goBack);
}

function getAll(sql) {
    let channelMsg = {
        type: "store",
        cmd: "sqliteGetAll",
        sql: sql,
    };
    return sendMsg(channelMsg);
}

function sqlliteExecute(sql) {
    let channelMsg = {
        type: "store",
        cmd: "sqlliteExecute",
        sql: sql,
    };
    return sendMsg(channelMsg);
}
function sqliteInsert(data) {
    let channelMsg = {
        type: "store",
        cmd: "sqliteInsert",
        sql: data["sql"],
        param: data["param"],
    };
    return sendMsg(channelMsg);
}

function getByLabel(data) {
    let channelMsg = {
        type: "store",
        cmd: "sqliteGetByLabel",
        sql: data["sql"],
        text: data["value"],
    };
    return sendMsg(channelMsg);
}

function sqlInit() {
    let channelMsg = {
        type: "store",
        cmd: "sqliteInitTable",
        table: "clipboard",
        sql: "create table clipboard(id integer PRIMARY KEY AUTOINCREMENT , name varchar(15), value varchar(65535), parentId integer);",
    };
    sendMsg(channelMsg);
}

async function listenerClipboard() {
    let text = clipboard.readText();
    let oldObj = await getByLabel({
        sql: "select * from clipboard where value = ?",
        value: text,
    });
    //查询剪切板是否存在
    if (!oldObj) {
        let clipboardObj = await getAll(
            "select * from clipboard where value = '剪切板'"
        );
        if (clipboardObj.length == 0) {
            await sqlliteExecute(
                "insert into clipboard (name, parentId, value) values('', 0, '剪切板')"
            );
            clipboardObj = await getAll(
                "select * from clipboard where value = '剪切板'"
            );
        }
        let sub = await getAll(
            `select * from clipboard where parentId=${clipboardObj[0].id}`
        );
        if (text.length > 65535) {
            return;
        }
        let sql = `insert into clipboard (name, value, parentId) values(?, ?, ?)`;
        //超过10个删除一个
        if (sub.length >= 10) {
            sqlliteExecute(`delete from clipboard where id=${sub[0].id}`);

            await sqliteInsert({
                sql: sql,
                param: ["", text, clipboardObj[0].id],
            });
        } else {
            await sqliteInsert({
                sql: sql,
                param: ["", text, clipboardObj[0].id],
            });
        }
    }
}

//外部应用创建的头部信息
Vue.component("my-menu", {
    data: function () {
        return {
            isTop: 0,
        };
    },
    mounted() {
        let data = {
            type: "main",
            cmd: "getIsAppTop",
        };
        this.send(data).then((res) => {
            this.isTop = res;
        });
    },
    methods: {
        send(data) {
            return sendMsg(data);
        },
        handleOpen() {},
        handleSelect(key, keyPath) {
            if (key == "top") {
                let data = {
                    type: "main",
                    cmd: "appTop",
                    isTop: this.isTop,
                };
                this.send(data).then((res) => {
                    this.isTop = res;
                });
            }
            if (key == "console") {
                let data = {
                    type: "main",
                    cmd: "showConsole",
                };
                this.send(data);
            }
        },
    },
    template: `<div <el-menu  mode="horizontal" @open="handleOpen" @select="handleSelect" background-color="#ffffff" text-color="#131313" active-text-color="none">
    <el-submenu index="setting">
        <template slot="title">设置</template>
        <el-menu-item index="console">控制台</el-menu-item>
        <el-menu-item index="top" v-text="isTop == 0 ? '应用置顶' : '取消置顶'"></el-menu-item>
    </el-submenu>
</el-menu> </div>`,
});

function getQueryString(name) {
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    let r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    }
    return null;
}

function calculatingTime() {
    listenerClipboard();
    sendMsg({ cmd: "getAll", db: "up_data", type: "store" }).then((res) => {
        defTime = utils.getCurrentDate();
        if (!res) {
            return;
        }
        let up_data = res.data;
        let new_data = JSON.parse(JSON.stringify(up_data));
        for (let id in new_data) {
            let now = new Date(); //当前时间
            let ns = new Date(new_data[id].datetime).getTime() - now.getTime(); //毫秒差

            if (ns > 1000) {
                ns -= 1000; //计算出相差天数
                let day = Math.floor(ns / (24 * 3600 * 1000)); //计算出小时数
                let leave1 = ns % (24 * 3600 * 1000); //计算天数后剩余的毫秒数
                let hour = Math.floor(leave1 / (3600 * 1000)); //计算出分钟数
                let leave2 = leave1 % (3600 * 1000); //计算小时后剩余的毫秒数
                let minutes = Math.floor(leave2 / (60 * 1000)); //计算出秒数
                let leave3 = leave2 % (60 * 1000); //计算分钟后剩余的毫秒数
                let second = Math.floor(leave3 / 1000);
                new_data[id].timeLeft =
                    "剩余：" +
                    day +
                    "天" +
                    hour +
                    "时" +
                    minutes +
                    "分" +
                    second +
                    "秒";
            } else {
                new_data[id].timeLeft = "剩余：0天0时0分0秒";
                if (new_data[id].show == 0) {
                    new_data[id].show = 1;
                    new Notification("工作内容", {
                        body: new_data[id].text,
                    });
                    let url = window.location.href;

                    let data = {
                        type: "store",
                        cmd: "show",
                    };
                    if (url.indexOf("index.html") > -1) {
                        data["url"] = "./view/upcoming/upcoming.html";
                    }
                    sendMsg(data);

                    let item = {
                        cmd: "set",
                        type: "store",
                        db: "up_data",
                        key: `up_data.${id}`,
                        value: new_data[id],
                    };
                    sendMsg(item);
                }
            }
        }
    });
}

function injection() {
    var t = setTimeout(function () {
        if (window.location.href.indexOf("http") == -1) {
            return;
        }

        escapeHTMLPolicy = trustedTypes.createPolicy("forceInner", {
            createHTML: (to_escape) => to_escape,
        });
        let Cpn = {
            template: `<div><my-menu></my-menu></div>`,
            data() {
                return {
                    message: "我是组件",
                };
            },
        };
        let head = null;
        try {
            head = document.querySelector("head");
        } catch {
            clearTimeout(t);
        }

        let style = document.createElement("link");
        //注入外部应用el ui样式
        style.innerHTML = escapeHTMLPolicy.createHTML(
            '<link rel="stylesheet" href=" https://unpkg.com/element-ui@2.15.9/lib/theme-chalk/index.css">'
        );

        let headcss = document.createElement("style");
        headcss.innerText = `.el-menu--horizontal>.el-submenu .el-submenu__title {
            height: 30px;
            line-height: 30px;
            border-bottom: 2px solid transparent;
            color: #909399;
        }
        
        .el-menu--horizontal>.el-menu-item {
            float: left;
            height: 30px;
            line-height: 30px;
            margin: 0;
            border-bottom: 2px solid transparent;
            color: #909399
        }
    
        .el-submenu__title {
            height: 30px !important;
            line-height: 30px !important;
            font-size: 14px;
            color: #303133;
            padding: 0 20px;
            list-style: none;
            cursor: pointer;
            position: relative;
            -webkit-transition: border-color .3s, background-color .3s, color .3s;
            transition: border-color .3s, background-color .3s, color .3s;
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
            white-space: nowrap;
        }

        
        .el-menu-item {
            height: 30px;
            line-height: 30px;
            font-size: 11px;
            color: #303133;
            padding: 0 20px;
            list-style: none;
            cursor: pointer;
            position: relative;
            -webkit-transition: border-color .3s, background-color .3s, color .3s;
            transition: border-color .3s, background-color .3s, color .3s;
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
            white-space: nowrap;
        }
        
        .el-submenu .el-menu-item {
            height: 30px !important;
            line-height: 30px !important;
            padding-left: 34px !important;
            min-width: 100px !important;
            padding: 0 45px;
            min-width: 50px;
            font-size: 11px !important;
        }

        .el-menu--popup {
            z-index: 100;
            min-width: 100px !important;
            border: none;
            padding: 5px 0;
            border-radius: 2px;
            -webkit-box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
            box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
        }
        
        @media (min-width: 480px) {
            :root {
                --main-container-width: 435px;
                --left-container-width: 158px;
            }
        }

        @media (min-width: 560px) {
            :root {
                --main-container-width: 560px;
                --left-container-width: 158px;
            }
        }


        @media (min-width: 1280px) {
            :root {
                --main-container-width: 650px;
                --left-container-width: 158px;
            }
        }   

        @media (min-width: 768px) {
            :root {
                --main-container-width: 760px;
                --left-container-width: 158px;
            }
        }`;

        head.appendChild(style);
        head.appendChild(headcss);
        let main = document.querySelector("body");

        if (window.location.href.indexOf("youdao") > -1) {
            let app = document.createElement("div");

            //创建vue节点
            let youdaoEL = document.querySelector("div");

            app.id = "app";
            main.insertBefore(app, youdaoEL);
            new Vue({
                el: "#app",
                render: function (createElement) {
                    //2.使用组件
                    let el = createElement(Cpn);
                    return el;
                },
                mounted: function () {
                    let from = getQueryString("trigger");
                    $ = require("jquery");
                    console.log($);
                    if (from) {
                        document.querySelector("#js_fanyi_input").innerText =
                            clipboard.readText();
                    }
                },
            });

            let back = document.querySelector(".tab-item.active.color_text_1");
            // back.innerHTML = '<i class="el-icon-back back">返回</i>';
            back.innerText = "返回";
            back.classList.remove("active");

            back.style.fontSize = "14px";

            regBack(back);
            $ = require("jquery");
            $(".footer").remove();

            // document.querySelector(".inside__products").remove();
            // document.querySelector(".fanyi__footer").remove();
            // document.querySelectorAll("a").forEach((dom) => {
            //     dom.onclick = () => {
            //         return false;
            //     };
            // });
        }
    }, 3000);
}

let url = window.location.href;

if (url.indexOf("youdao") > -1) {
    ipcRenderer.on("main", (_event, res) => {
        document.querySelector("#js_fanyi_input").innerText =
            clipboard.readText();
    });
} else {
    ipcRenderer.on("main", (_event, res) => {
        //在首页点击 翻译图标
        if (res.cmd == "translation") {
            let data = {
                cmd: "open",
                type: "main",
                url: "https://fanyi.youdao.com/index.html?trigger=1",
            };
            sendMsg(data);
        }
    });
}

getAll("select * from clipboard where value = '剪切板'");

injection();
sqlInit();
setInterval(calculatingTime, 900);
